package com.wnhoo.smartfishtank.fishtank;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wnhoo.smartfishtank.R;
import com.wnhoo.smartfishtank.api.LM_PlugAPIs;
import com.wnhoo.smartfishtank.api.data.LM_DataAddDelEdit;
import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.base.BaseActivity;
import com.wnhoo.smartfishtank.util.ShowToastUtil;

import java.io.UnsupportedEncodingException;

public class Light_SettingActivity extends BaseActivity implements BaseActivity.InitHeaderListener {

    private RelativeLayout light_edit_timing, light_edit_name_rel, light_setting_rel_del;
    private TextView light_edit_name_tv, light_setting_tv_del;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light_setting);
        setOnInitListener(this);
        initView();
        initData();
    }

    private void initData() {
        light_edit_name_tv.setText(LMAPP.dataPlug.getTitle());
    }

    @Override
    public void initView() {
        super.initView();
        light_edit_timing = (RelativeLayout) findViewById(R.id.light_edit_timing);
        light_edit_name_rel = (RelativeLayout) findViewById(R.id.light_edit_name_rel);
        light_setting_rel_del = (RelativeLayout) findViewById(R.id.light_setting_rel_del);
        light_edit_name_tv = (TextView) findViewById(R.id.light_edit_name_tv);
        light_setting_tv_del = (TextView) findViewById(R.id.light_setting_tv_del);
        light_edit_timing.setOnClickListener(this);
        light_edit_name_rel.setOnClickListener(this);
        light_setting_rel_del.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.light_edit_timing:
                Log.e(TAG, "------- 000 ------");
                startActivity(new Intent(this, Light_Timing_ListActivity.class));
                break;
            case R.id.light_edit_name_rel:
                showAlterNameView();
                break;
            case R.id.light_setting_rel_del:
                showDeleteView();
                break;
        }
    }

    /**
     * 显示修改
     */
    private void showAlterNameView() {
        View view_edit = View.inflate(this, R.layout.sub_edittext, null);
        final EditText editview_name = (EditText) view_edit.findViewById(R.id.editview_name);
        editview_name.setText(LMAPP.dataPlug.getTitle());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getStringXml(R.string.modify)).setView(view_edit)
                .setNegativeButton(getStringXml(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.setPositiveButton(getStringXml(R.string.ok), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                name = editview_name.getText().toString();
                EditDevice();
            }
        });
        builder.show();
    }

    /**
     * 显示删除
     */
    private void showDeleteView() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getStringXml(R.string.prompt)).setMessage(getStringXml(R.string.del_device_mess))
                .setNegativeButton(getStringXml(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.setPositiveButton(getStringXml(R.string.ok), new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                delDevice();
            }
        });
        builder.show();
    }

    @Override
    public void OnSetTitle(TextView t) {
        t.setTextColor(this.getResources().getColor(R.color.ther_text_color));
        t.setText(getStringXml(R.string.setting));
    }

    @Override
    public void OnSetLeftView(Button btn) {
        btn.setVisibility(View.VISIBLE);
    }

    @Override
    public void OnSetRightView(Button btn) {

    }

    @Override
    public void OnSetLeftOnclick(View view) {
    }

    @Override
    public void OnSetRightOnclick(View view) {

    }

    @Override
    public void onSetbackground(View view) {
        view.setBackgroundResource(R.drawable.solid_shadow);
    }

    private final static int MSG_HTTP_SEND_EDIT_RESULT = 1;//修改结果返回
    private final static int MSG_HTTP_SEND_DEL_RESULT = 2;//删除结果返回
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            LM_DataAddDelEdit lm_dataAddDelEdit = (LM_DataAddDelEdit) msg.obj;
            switch (msg.what) {
                case MSG_HTTP_SEND_EDIT_RESULT:
                    //handlerSendResult(msg);
                    if (lm_dataAddDelEdit.getError_code() == 0) {
                        ShowToastUtil.show(getApplication(),getStringXml(R.string.edit_success));
                        light_edit_name_tv.setText(name);
                        LMAPP.dataPlug.setTitle(name);
                        LMAPP.saveMemoryPlugToSPF();
                    } else {
                        ShowToastUtil.show(getApplication(),getStringXml(R.string.edit_fail));
                    }
                    break;
                case MSG_HTTP_SEND_DEL_RESULT:
                    //handlerSendResult(msg);
                    if (lm_dataAddDelEdit.getError_code() == 0) {
                        ShowToastUtil.show(getApplication(),getStringXml(R.string.del_success));
                        LMAPP.deletePlug(LMAPP.dataPlug);
                        Intent intent = new Intent(Light_SettingActivity.this, DataPlug_ListActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        startActivity(intent);
                    } else {
                        ShowToastUtil.show(getApplication(),getStringXml(R.string.del_fail));
                    }
                    break;
            }
        }
    };

    //删除设备
    public void delDevice() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    LM_DataAddDelEdit dataDel = LM_PlugAPIs.deviceDel(true, LMAPP.dataPlug.getId(), LMAPP.token_default);
//                    Log.i(TAG, "lm_dataPlugList" + lm_dataPlugList.getData().toString());
                    sendMessageToUI(MSG_HTTP_SEND_DEL_RESULT, dataDel);
                } catch (Exception e) {
                    e.printStackTrace();
//                    sendMessageToUI(MSG_HTTP_SEND_EXCEPTION, e);
                }
            }
        }.start();
    }

    //修改设备
    public void EditDevice() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    name = toUTF_8(name);
                    LM_DataAddDelEdit dataEdit = LM_PlugAPIs.deviceEdit(true, LMAPP.dataPlug.getId(), LMAPP.dataPlug.getType(), name, LMAPP.token_default);
                    Log.i(TAG, "lm_dataPlugList" + dataEdit.toString());
                    sendMessageToUI(MSG_HTTP_SEND_EDIT_RESULT, dataEdit);
                } catch (Exception e) {
                    e.printStackTrace();
//                    sendMessageToUI(MSG_HTTP_SEND_EXCEPTION, e);
                }
            }
        }.start();
    }
    /**
     * 将字符编码转换成UTF-8码
     */
    public String toUTF_8(String str) throws UnsupportedEncodingException {
        return this.changeCharset(str, "utf-8");
    }
    /**
     * 字符串编码转换的实现方法
     * @param str  待转换编码的字符串
     * @param newCharset 目标编码
     * @return
     * @throws UnsupportedEncodingException
     */
    public String changeCharset(String str, String newCharset)
            throws UnsupportedEncodingException {
        if (str != null) {
            //用默认字符编码解码字符串。
            byte[] bs = str.getBytes();
            //用新的字符编码生成字符串
            return new String(bs, newCharset);
        }
        return null;
    }
    public void sendMessageToUI(int what, Object obj) {

        Message message = Message.obtain();
        message.what = what;
        message.obj = obj;
        handler.sendMessage(message);
    }
}
